<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="入库单编号" prop="rtCode">
        <el-input
          v-model="queryParams.rtCode"
          placeholder="请输入入库单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单名称" prop="rtName">
        <el-input
          v-model="queryParams.rtName"
          placeholder="请输入入库单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库日期" prop="params">
        <el-date-picker
          clearable
          v-model="queryParams.params"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:rtissueother:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-card style="border-radius: 10px">
    <el-table v-loading="loading" :data="rtissueotherList" @selection-change="handleSelectionChange" border>
      <el-table-column label="入库单编号"  align="center" prop="rtCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['wm:rtissueother:query']"
          >{{ scope.row.rtCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="入库单名称"  align="center" prop="rtName" :show-overflow-tooltip="true"/>
      <el-table-column label="入库日期" align="center" prop="rtDate" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rtDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">

            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              v-if="scope.row.status =='CONFIRMED'"
              @click="handleExecute(scope.row)"
              v-hasPermi="['wm:rtissueother:execute']"
            >执行入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-if="scope.row.status =='PREPARE'"
            @click="handleConfirme(scope.row)"
            v-hasPermi="['wm:issueother:edit']"
          >确认</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status =='PREPARE'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['wm:rtissueother:edit']"
            >修改</el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="(scope.row.status =='PREPARE' || scope.row.status =='CONFIRMED') && (scope.row.rtIssueType !=='feiPinRuKu')"
              @click="handleDelete(scope.row)"
              v-hasPermi="['wm:rtissueother:remove']"
            >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改生产入库单头对话框:disabled="form.checkCode != '' && form.checkCode != null" -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form"  :rules="rules" label-width="100px"  >
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库单编号" prop="rtCode">
              <el-input v-model="form.rtCode"  placeholder="请输入入库单编号" :readonly="optType !== 'add'"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)" v-if="optType == 'add' && form.status =='PREPARE'">
              </el-switch>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="rtName">
              <el-input v-model="form.rtName" placeholder="请输入入库单名称" :disabled="disable"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="rtDate" >
              <el-date-picker clearable :disabled="optType == 'view'"
                              v-model="form.rtDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :default-value="new Date()"
                              placeholder="请选择入库日期"
                              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库类型" prop="rtIssueType">
<!--              <el-input v-model="form.rtIssueType" />-->
              <el-select v-model="form.rtIssueType" placeholder="请选择入库类型" @change="handleRtIssueTypeChange" :disabled="disable">
                <el-option
                  v-for="dict in dict.type.rtissueother_type.filter((item) => (item.value !== 'zuZhuangDan' || optType == 'view'))"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
<!--        项目这个比较特殊，关联项目 将项目编号存到checkCode中，然后将项目阶段(templateId)保存到关联单据id这个字段associateBillId  所以项目这个关联单据id不是对应项目编号的Id
         这个关联单据类型associate_bill_type就默认为项目-->
        <el-row v-if="form.rtIssueType == 'yanFaTuiLiao'">
          <el-col :span="12">
            <el-form-item  label="关联项目"  prop="associateBillType" :disabled="disable">
              <!--              <el-input v-model="form.associateBillType" />-->
              <el-input v-model="form.checkCode" >
                <el-button slot="append" icon="el-icon-search" @click="handleXMSelect" ></el-button>
              </el-input>
            </el-form-item>
          <xiang-mu ref="xiangMu" v-if="form.rtIssueType == 'yanFaTuiLiao'" @onSelected="onXiangMuSelected"></xiang-mu>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目阶段" prop="associateBillId">
<!--          :disabled="disable"    <el-input v-model="form.checkCode" > </el-input>-->
                <treeselect
                  :multiple="true"
                  :options="xiangmuJieDuans"
                  value-consists-of="LEAF_PRIORITY"
                  v-model="selectItemList"
                  placeholder="请选择项目阶段"
                  @input="handleInput"
                  value-format="object"
                />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.rtIssueType !== 'yanFaTuiLiao' && form.rtIssueType !== 'qiTa' && form.rtIssueType !== 'zuZhuangDan'">
          <el-col :span="12">
            <el-form-item  label="关联单据类型"  prop="associateBillType">
<!--              <el-input v-model="form.associateBillType" />-->
              <el-select v-model="form.associateBillType" placeholder="单据类型"  clearable :disabled="disable">
                <el-option
                  v-for="(billType,index) in  billTypeList"
                  :key="billType.dictValue"
                  :label="billType.dictLabel"
                  :value="billType.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联单据编号" prop="checkCode">
              <el-input v-model="form.checkCode" :disabled="disable">
                <el-button slot="append" icon="el-icon-search" @click="handleBillSelect" ></el-button>
              </el-input>
            </el-form-item>
<!--       v-if="form.associateBillType =='weiXiuDan' "      <bill-choose ref="billchoose" @onSelected="onBillSelected"></bill-choose>-->
            <wei-xiu ref="weiXiuDan" v-if="form.associateBillType =='weiXiuDan'" @onSelected="onWeiXiuSelected"></wei-xiu>
            <dian-jian ref="dianJianDan" v-if="form.associateBillType =='dianJianDan'" @onSelected="onDianJianSelected"></dian-jian>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请填写入库原因" :disabled="disable"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="form.rtId !=null" content-position="center">物料信息</el-divider>
      <el-card shadow="always" v-if="form.rtId !=null" class="box-card">
        <Rtissueline :rtId="form.rtId" :optType="optType" :workorderId="form.workorderId" :rtCheckCode="form.checkCode" :rtIssueType="form.rtIssueType" @custom="handleChildEvent"></Rtissueline>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRtissueother,
  delRtissueother,
  execute,
  getRtissueother,
  listRtissueother,
  updateRtissueother,
  selectTree,
  confirmRt,
  processList
} from "@/api/mes/wm/rtissueother";
import Rtissueline from "@/views/mes/wm/rtissueother/line";
import { genCode } from "@/api/system/autocode/rule";
import { getTreeList } from "@/api/mes/wm/warehouse";
import {getDicts} from "@/api/system/dict/data"
import WeiXiu from "@/views/mes/wm/rtissueother/bill/weixiu.vue"
import DianJian from "@/views/mes/wm/rtissueother/bill/dianjian.vue"
import XiangMu from "@/views/mes/wm/rtissueother/bill/xiangmu.vue"
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {confirme} from "@/api/mes/wm/issueother";
export default {
  name: "Rtissueother",
  dicts: ['mes_order_status','rtissueother_type'],
  components: {Treeselect, Rtissueline,WeiXiu,DianJian,XiangMu},
  data() {
    return {
      disable:false,
      isShow:false,
      xiangmuJieDuans:[],
      selectItemList:[],
      billTypeList:[],
      autoGenFlag: false,
      optType: undefined,
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产入库单头表格数据
      rtissueotherList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rtCode: null,
        rtName: null,
        workorderId: null,
        workorderCode: null,
        taskId: null,
        taskCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        rtDate: null,
        status: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        params: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rtCode: [
          {required: true, message: "入库单编号不能为空", trigger: "blur"}
        ],
      /*  remark: [
          {required: true, message: "备注不能为空", trigger: "blur"}
        ],*/
        rtIssueType: [
          {required: true, message: "入库类型不能为空", trigger: "blur"}
        ],
        rtName: [
          {required: true, message: "入库名称不能为空", trigger: "blur"}
        ],
        rtDate: [
          {required: true, message: "入库日期不能为空", trigger: "blur"}
        ]
      },
      fpck: false
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    /** 查询生产入库单头列表 */
    getList() {
      this.loading = true;
      const query = { ...this.queryParams };
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      listRtissueother(query).then(response => {
        this.rtissueotherList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //选择单据显示 ref="" 这个就跟字段里的一样
    handleBillSelect(){
      // this.$refs.dianJianDan.showFlag=true
      if(this.form.associateBillType && this.form.rtIssueType){
        const refName=this.form.associateBillType
        console.log("sssssss",refName)
        this.$refs[refName].showFlag = true;
      }else{
        this.$modal.msgWarning("请填写【入库类型】和【关联单据类型】");
      }

      // this.isShow=true
    },
    //项目 研发退料跟其他不同，
    handleXMSelect(){
      this.$refs.xiangMu.showFlag = true;

    },
      // 每种单据的id用的字段都不同，每个都得写一下
    // 维修单
    onWeiXiuSelected(row){
      if(row != undefined && row != null){
        this.form.associateBillId = row.repairId;
        this.form.checkCode = row.repairCode;
      }
    },
    // 点检单
    onDianJianSelected(row){
      if(row != undefined && row != null){
        this.form.associateBillId = row.recordId;
        this.form.checkCode = row.recordCode;
      }
    },
    //项目
    onXiangMuSelected(row){
      if(row != undefined && row != null){
        // this.form.associateBillId = row.id;
        this.form.checkCode = row.projectCode;
        selectTree({"id":row.templateId}).then(response =>{

          this.xiangmuJieDuans=response.data.tree
          console.log("1111111111111111111111111111111",response.data.tree)
        })
        this.$forceUpdate()
      }

    },
    handleInput(selectedNodes){
      console.log("11111111111",selectedNodes)
      // 获取所有id
      var ids = selectedNodes.map(function(item) {
        return item.id;
      });
      console.log("IDs:", ids);
// 获取所有label
      var labels = selectedNodes.map(function(item) {
        return item.label;
      });
      console.log("Labels:", labels);
      this.form.associateBillId=ids.join(",")
      // this.form.itemTypeNameRange=labels.join(",")
    },
    //入库类型发生变化
    handleRtIssueTypeChange(value){
      //入库类型为研发入库
      this.selectItemList=[]
      this.xiangmuJieDuans=[]
      this.form.associateBillType=''
      this.form.checkCode=''
      this.billTypeList=[];
      getDicts(value).then(response => {
        this.billTypeList=response.data
      })
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
          ;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rtId: null,
        rtCode: null,
        rtName: null,
        workorderId: null,
        workorderCode: null,
        taskId: null,
        taskCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        rtDate: new Date().toISOString().split('T')[0],
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null,
        checkCode:null,
        rtIssueType:'qiTa',
        associateBillType:null,
        associateBillId:null
      };
      this.autoGenFlag = false;
      this.resetForm("form");
      this.disable=false
      this.xiangmuJieDuans=[]
    },
    //确认
    handleConfirme(row) {
      const rtId = row.rtId || this.ids
      this.$modal.confirm('对该入库单进行确认？').then(function () {
        return confirmRt(rtId)//确认
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("确认成功");
      }).catch(() => {
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rtId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('RTISSUE_OTHER_CODE').then(response => {
        this.form.rtCode = response;
      });
      this.open = true;
      this.title = "添加入库单头";
      this.optType = "add";
      console.log("22222222222222",this.form.checkCode)
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.disable=true
      const rtIds = row.rtId
      getRtissueother(rtIds).then(response => {
        this.form = response.data;
        this.warehouseInfo[ 0 ] = response.data.warehouseId;
        this.warehouseInfo[ 1 ] = response.data.locationId;
        this.warehouseInfo[ 2 ] = response.data.areaId;
        //获取关联单据类型
        this.billTypeList=[]
        getDicts(response.data.rtIssueType).then(response => {
          this.billTypeList=response.data
        })
        this.open = true;
        this.title = "查看入库单信息";
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disable=true
      const rtId = row.rtId || this.ids
      getRtissueother(rtId).then(response => {
        this.form = response.data;
        console.log("3333333333",this.form.rtIssueType)
        this.warehouseInfo[ 0 ] = response.data.warehouseId;
        this.warehouseInfo[ 1 ] = response.data.locationId;
        this.warehouseInfo[ 2 ] = response.data.areaId;
        //获取关联单据类型
        this.billTypeList=[]
        console.log("response.data.rtIssueType",response.data.rtIssueType)
        getDicts(response.data.rtIssueType).then(response => {
          this.billTypeList=response.data
          console.log("response.data",response.data)
        })
        if('yanFaTuiLiao' == response.data.rtIssueType){
          this.xiangmuJieDuans=[]
          // const  selectedIds=response.data.associateBillId.split(",")
          const selectedIds = response.data.associateBillId.split(',').map(id => parseInt(id, 10));
          processList({projectCode: response.data.checkCode}).then(responseP => {
            const projectInfo = responseP.rows[0];
            selectTree({"id":projectInfo.templateId}).then(res =>{
              //赋值给list
              this.xiangmuJieDuans = res.data.tree
              console.log("33333333",selectedIds)
              // 转换ID数组为treeselect需要的对象格式
          /*    this.selectItemList =[ { id: 167, label: "需求调研" },
              { id: 168, label: "产品设计" }]*/
              this.selectItemList = this.xiangmuJieDuans
                .flatMap(item => item.children || [])
                .filter(child => selectedIds.includes(child.id))
                .map(({ id, label }) => ({ id, label }));

              console.log("1111111111111111111111111111111",this.selectItemList)
              console.log("22222222222222222",res.data.tree)

            })
          });
        }
        console.log("tttttttttttttt",this.billTypeList)
        this.open = true;
        this.title = "修改入库单头";
        this.optType = "edit";
      });
    },


    // 扁平化树结构数据
    flattenTree(nodes) {
      let result = [];
      nodes.forEach(node => {
        result.push(node);
        if (node.children && node.children.length) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    /*用于校验废品入库 仓库是否添加
    */
    handleChildEvent(data) {
      this.fpck = data
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs[ "form" ].validate(valid => {
        if (valid) {
          if (this.form.rtId != null ) {
            console.log('============',this.fpck)
            if(this.fpck){
              updateRtissueother(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else{
              this.$modal.msgWarning("请填写仓库、库区、库位");
            }

          } else {
            addRtissueother(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rtIds = row.rtId || this.ids;
      this.$modal.confirm('是否确认删除生产入库单头编号为"' + rtIds + '"的数据项？').then(function () {
        return delRtissueother(rtIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/rtissueother/export', {
        ...this.queryParams
      }, `rtissueother_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('RTISSUE_OTHER_CODE').then(response => {
          this.form.rtCode = response;
        });
      } else {
        this.form.rtCode = null;
      }
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      if (obj != null) {
        this.form.warehouseId = obj[ 0 ];
        this.form.locationId = obj[ 1 ];
        this.form.areaId = obj[ 2 ];
      }
    },
    //执行入库
    handleExecute(row) {
      const rtIds = row.rtId || this.ids;
      this.$modal.confirm('确认执行入库？').then(function () {
        return execute(rtIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => {
      });
    },
  }
};
</script>
